/**
* Misc functions
*/
function fg_findPos( p ) {
	var left = 0;
	var top = 0;

	var left = p.offsetLeft
	var top = p.offsetTop+10;
	
	for (; p; p = p.offsetParent){
		top+= p.offsetTop;
		left += p.offsetLeft;
	}
	return [left,top];
}

function fg_getElementWidth(Elem) {
	if ( ns4 ) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.width;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) {
			xPos = elem.style.pixelWidth;
		} else {
			xPos = elem.offsetWidth;
		}
		return xPos;
	}
}

function fg_getElementHeight(Elem) {
	if ( ns4 ) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.height;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) { 
			xPos = elem.style.pixelHeight;
		} else {
			xPos = elem.offsetHeight;
		}
		return xPos;
	} 
}

// Temporary variables to hold mouse x-y pos.s
var fg_mouseX = 0
var fg_mouseY = 0
document.onmousemove = captureMouseXY;
if ( !document.all ) 
	document.captureEvents(Event.MOUSEMOVE)

function captureMouseXY(e) {

	if ( document.all ) { // grab the x-y pos.s if browser is IE
		fg_mouseX = event.clientX + document.body.scrollLeft
		fg_mouseY = event.clientY + document.body.scrollTop
	} else {  // grab the x-y pos.s if browser is NS
		fg_mouseX = e.pageX
		fg_mouseY = e.pageY
	}  
	
	// catch possible negative values in NS4
	if (fg_mouseX < 0) fg_mouseX = 0;
	if (fg_mouseY < 0) fg_mouseY = 0;  
	
	return true;
}

function getMouseXY() {
	return [fg_mouseX,fg_mouseY];
}

/**
* Function that toggles tab menu
*/
function fg_showTab( group, tabId, tabNr ) {
	eval("var tabs="+group+";");
	//document.getElementsByName( group+"_name" );

	for( i=0; i<tabs.length; i++) {
		tab = document.getElementById( tabs[i] );
		if( tab.id == tabId ) {
			tab.className = 'selected';
			document.getElementById(tab.id+"_frame").style.display = "";
		} else {
			tab.className = '';
			document.getElementById(tab.id+"_frame").style.display = "none";
		}
	}
	
	document.getElementById(group + "_selectedTab").value = tabNr;
}

/**
* Handles submit button clicks.
*/
function fg_submit( element, name, value, action, target ) {
	$(element).append('<input type="hidden" id="'+name+'-id" name="'+name+'" value="'+value+'" />');
	var button = document.getElementById( name + "-id" );
	button.value = value;
	if( action != null)
		button.form.action = action;
	button.form.submit();
}


function fg_confirm( message, to, target ) {
	if( confirm(message) ) {
		document.location = to;
	}
}

function fg_open( to, target ) {
	if( confirm(message) ) {
		document.location = to;
	}
}

function fg_button_click( element, name, value, link, submitLink, target, confirmMessage ) {
	
	if( confirmMessage != '' && confirmMessage != null ) {
		if( confirm(confirmMessage) == false ) {
			return;
		}
	}
	
	if (link != '') {
		if (target == '_blank') {
			var newWindow = window.open(link, '_blank');
			newWindow.focus();
		}
		else {
			document.location = link;
		}
	} else {
		$(element).append('<input type="hidden" id="' + name + '-id" name="' + name + '" value="' + value + '" />');
		var button = document.getElementById(name + "-id");
		button.value = value;
		if( submitLink != "" && submitLink != null) {
			button.form.action = submitLink;
		}
		button.form.submit();
	}
	
}

/**
* Html editor image manager handling function
* @author Oliver Leisalu
* @package DomFg 
* @created 11.11.2009
*/
function updateHtmlEditorImage( id, url ) {
	window.opener.document.updateContent(id, url);
}

/**
* Panel
* @author Oliver Leisalu
* @package DomFg 
* @created 11.11.2009
*/
$.fn.fg_panel = function(options){
	
	var defaults = {
		'id' : '',
		'closed': false
	};
	
	var options = $.extend( defaults, options ); 
	
	var panelHeader = $("#panelHeader_"+options.id);
	var panelContent = $("#panelContent_"+options.id);
	
	if( options.closed ) {
		panelContent.slideToggle(0);
	}
		
	panelHeader.click( function() {
		panelContent.slideToggle(500);
	});

}



/**
Drop down menu maker
@author Oliver Leisalu
@package DomFg 
@created 16.06.2008
*/
DomFgMenu = function( uid ) {
	
	this.uid = uid;
	
	this.reactionTime = 250;
	this.timeout = -1;
	this.oTd = null;
	
	this.doMenu = function(td){
		clearTimeout(this.timeout);
		var i;
		var sT="";
		var tda=new Array();
		var tda = td.id.split("_");
		if(this.oTd!=null){
			var tdo=new Array();
			tdo=this.oTd.id.split("_");
			for(i=1;i<tdo.length;i++){
				sT+="_"+tdo[i];
				if(tdo[i]!=tda[i]){
					if(document.getElementById(this.uid+"tbl"+sT)!=null) {
						document.getElementById(this.uid+"tbl"+sT).style.visibility="hidden";
						document.getElementById(this.uid+"td"+sT).className = "";
					}
				}
			}			
		}
		
		this.oTd=td;
		sT="";
		for(i=1;i<tda.length;i++)
			sT+="_"+tda[i];
	
		if(document.getElementById(this.uid+"tbl"+sT)!=null) {
			document.getElementById(this.uid+"tbl"+sT).style.visibility="visible";
			document.getElementById(this.uid+"td"+sT).className = "selected";
			//this.setPos( this.uid+"tbl"+sT );
		}
	}
	
	this.clearMenu = function(){
		if(this.oTd!=null){
			var tdo=new Array();
			tdo=this.oTd.id.split("_");
			var sT="";
			for(var i=1;i<tdo.length;i++){
				sT+="_"+tdo[i];
				if(document.getElementById(this.uid+"tbl"+sT)!=null) {
					document.getElementById(this.uid+"tbl"+sT).style.visibility="hidden";
					document.getElementById(this.uid+"td"+sT).className = "";
				}
			}
			this.oTd=null;			
		}
	}
	
	//this.tt="";
	//this.sT="";
	//this.pT=new Array();
	//this.tA=new Array();

	this.setPos = function( st ) {
		var pos = this.findPos( st );
		var element = document.getElementById( st );
	//	alert(st+": top:"+pos.top+"px;left:"+pos.left+"px")
		//alert(element.id)
		element.style.left = pos.left+"px";
		element.style.top = pos.top+"px";
		if( element.id == 'menu2tbl_0_1') {
			//alert('hei')
		}
	}
	
	this.findPos = function ( st ) {
		var tA = st.split("_");
		
		if( tA.length > 2 ){
			tA = tA.slice(0,-1);
			
			var tt = tA.join("_");
			var main = document.getElementById(this.uid+"tbl"+tt);
			var tile = document.getElementById(this.uid+"td"+st);
			var curleft = main.offsetWidth;
			var curtop = -1;
		} else {
			
			var main = document.getElementById(this.uid+"mainmenu");
			var tile = document.getElementById(this.uid+"td"+st);
			var curleft = 5;
			var curtop = tile.offsetHeight;
		}
		
		
		
		do {
			curleft += tile.offsetLeft;
			curtop += tile.offsetTop;
		} while ( tile = tile.offsetParent )
		
		//alert(st+": top:"+curtop+"px;left:"+curleft+"px")
		return {top:curtop,left:curleft}
		//return "top:"+curtop+"px;left:"+curleft+"px";
	}

	this.menuMouseOut = function() {
		this.timeout = setTimeout(this.uid+".clearMenu()", this.reactionTime )
	}
	
	this.drawMenu = function( menu, parentId ) {
		
		var drawMain = parentId == 0;
	
		if( drawMain == true ) {
			var id = this.uid+"mainmenu";
			var className = "fg_menu";
			var parentId = "";
			var style = "";
		} else {
			var id = this.uid+"tbl"+parentId;
			var className = "fg_submenu";
			var pos = this.findPos( parentId );
			var style = "top:"+pos.top+"px;left:"+pos.left+"px";
		}
	
		var html = "<div id=\""+id+"\" class=\""+className+"\" style=\""+style+"\">";
		for( var i=0; i<menu.length; i++) {
	
			if( menu[i] ) {
				if( menu[i][0] == "separator" ) {
					html += "<div class=\"fg_menuSeparator\"></div>";
				} else {
					html += "<a id=\""+this.uid+"td"+parentId+"_"+i+"\" onmouseover=\""+this.uid+".doMenu(this)\" onmouseout=\""+this.uid+".menuMouseOut()\" href=\""+menu[i][1]+"\">";
					html += "<span class=\"fg_border\">";
					html += "<span class=\"fg_icon\">";
					if( drawMain == false && menu[i][2] != "" )
						html += "<img src=\""+menu[i][2]+"\" />";
					html += "</span>";
					html += "<span class=\""+(menu[i][3].length > 0 ? "fg_hasSubs" : "")+"\">"+menu[i][0]+"</span>";
					html += "</span>";
					html += "</a>";
				}
			}
		}
	
		document.write( html + "</div>" );
	
		for( var i=0; i<menu.length; i++) {
			if( menu[i] && menu[i][3].length > 0 )
				this.drawMenu( menu[i][3], parentId+"_"+i );
		}
	
		//document.getElementById(uid+"mainmenu").style.visibility="visible";
	}
}


/**
DomFgSearchSelect handler
@author Oliver Leisalu
@package DomFg 
@created 16.06.2008
*/

function fg_searchSelect( name, url, maxElements, allowAddingNew ) {
	
	this.name = name;
	this.url = url;
	
	this.searchElement = document.getElementById( name+"_search");
	this.keysElement = document.getElementById( name+"_keys");
	this.valuesElement = document.getElementById( name+"_values");
	
	this.resultElement = document.getElementById( name+"_result");
	this.resultContentsElement = document.getElementById( name+"_resultContents");
	
	// Table where items are held
	this.tableElement = document.getElementById( name+"_table");
	// Message that says there are no elements
	this.noneElement = document.getElementById( name+"_none");
	
	this.maxElements = maxElements;
	this.allowAddingNew = allowAddingNew == 1 ? true : false;
	
	this.newCount = 0;
	

	this.search = function() {
		
		
		var url = this.url;
		var varPos = url.indexOf("[$search]");
		if( varPos > 0)
			url = url.substr(0,varPos) + this.searchElement.value + url.substr(varPos+9, url.length);
		else
			url += this.searchElement.value;
		
		eval("function onSuccess( data ) {"+this.name+"_searchObject.finishSearch( data ); }");
	
		jQuery.get( url, {}, onSuccess, 'text');
			
		pos = fg_findPos( this.searchElement );
		
		this.resultElement.style.left = pos[0]-5+"px";
		this.resultElement.style.top = pos[1]+8+"px";
		
		this.resultContentsElement.innerHTML = "Laen...";
		this.resultElement.style.display = "";

	}
	
	this.enterSearch = function ( e ) {
		var key = (navigator.appName == "Netscape") ? e.which : e.keyCode;
		if( key == 13 || key == 0) {
			this.search();
		}
	}
	
	this.makeValueSafe = function( str ) {
		var newStr = str;
		newStr = newStr.replace(/\"/g,"&quot;");
		newStr = newStr.replace(/\'/g,"\\'");
		return newStr;
	}
	
	this.finishSearch = function( responseText ) {
		
		var rows = eval( responseText )
		var contents = "";

		if( this.allowAddingNew == true && this.searchElement.value != "")
			contents += "<a href=\"javascript:"+this.name+"_searchObject.add('new','"+this.makeValueSafe(this.searchElement.value)+"')\"> Lisa uus: <b>"+this.searchElement.value+"</b></a><br /><br />";
		
		if( rows.length > 0) {
			contents += "<b>Leitud vasted</b><br /><ul class=\"fg_searchSelectList\">";
			for( i=0; i<rows.length-(document.all ? 1 : 0); i++) {
				contents += "<li><a href=\"javascript:"+this.name+"_searchObject.add('"+rows[i].key+"','"+this.makeValueSafe(rows[i].value)+"')\">"+(rows[i].showValue ? rows[i].showValue : rows[i].value)+"</a></li>";
			}
			contents += "</ul>";
		} else {
			contents += "<b>Ei leitud tulemusi!</b><br />";
		}
		this.resultContentsElement.innerHTML = contents;
	}
	
	this.hideResult = function() {
		this.resultElement.style.display = "none";
	}
	
	this.testIfAdded = function( id, name ) {
		el = this.keysElement.value.split("|");
		values = this.valuesElement.value.split("|");

		for( i=0; i<el.length; i++) {
			if( el[i] == id || values[i] == name ) {
				return true;
			}
		}
		return false;
		
	}
	
	this.add = function( id, value ) {
		
		this.resultElement.style.display = "none";
		
		// checking if max limit has been reached
		if( this.maxElements <= this.tableElement.rows.length-1 ) {
			alert("Rohkem ei ole lubatud lisada!");
		} else {
			// if new suggested changing key
			if( id == "new" ) {
				id = "new"+this.newCount;
				this.newCount++;
			}
			
			// checking, if item not already added
			if( this.testIfAdded( id, value ) == true) {
				alert("Juba lisatud!");
			} else {
				this.valuesElement.value += (this.valuesElement.value != "" ? "|" : "")+value;
				this.keysElement.value += (this.keysElement.value != "" ? "|" : "")+id;
				this.searchElement.value = "";
		
				var pos = this.tableElement.rows.length;
				this.tableElement.insertRow( pos );
				
				var row = this.tableElement.rows[pos];
				
				row.insertCell(0);
				row.insertCell(1);
				
				row.style.backgroundColor = "#FFFFFF";
				row.cells[0].innerHTML = value;
				row.cells[0].width = 190;
				row.cells[1].innerHTML = "<a href=\"javascript:"+this.name+"_searchObject.removeValue('"+id+"')\"  style=\"color:#990000\">Eemalda</a>";
				row.cells[1].width = 20;
				
				this.noneElement.style.display="none";
			}
		}
	}
	
	this.removeValue = function( id ) {
		el = this.keysElement.value.split("|");
		values = this.valuesElement.value.split("|");
		
		newValues = "";
		newKeys  = "";
		added = false;
		for( i=0; i<el.length; i++) {
			if( el[i] == id ) {
				this.tableElement.deleteRow(i+1)
			} else {
				newValues += (added == true ? "|" : "") + values[i];	
				newKeys += (added == true ? "|" : "") + el[i];	
				added = true;
			}
		}
		
		this.keysElement.value = newKeys;
		this.valuesElement.value = newValues;
		
		if( this.keysElement.value == "") {
			this.noneElement.style.display="";
		}
		
	}
}

/**
* Mp3Player
*/

function fg_replaceMp3Player( locationId, song, playerLocation ) {
	swfobject.embedSWF( playerLocation, locationId, "80", "18", "9.0.0", false, {song: song, playerLocation:playerLocation, playerName:locationId, allowscriptaccess: "always"} );
}
	
function fg_makeMp3PlayerLocation( id, song, playerLocation ){
	try {
		e = document.createElement("<div id="+id+" class=\"fg_mp3PlayerSub\" onclick=\"fg_replaceMp3Player(\'"+id+"\',\'"+song+"\',\'"+playerLocation+"\')\" />");
	} catch (er) {
		e = document.createElement("div");
		e.setAttribute("id", id);
		e.setAttribute("class", "fg_mp3PlayerSub");
		e.setAttribute("onclick","fg_replaceMp3Player(\'"+id+"\',\'"+song+"\',\'"+playerLocation+"\')");
	}
	t = document.getElementById( id+"Border" ).appendChild( e );
}

function fg_removeMp3Player( id, song, playerLocation  ) {
	document.getElementById( id+"Border" ).innerHTML = "";
	fg_makeMp3PlayerLocation( id, song, playerLocation );
}



/**
DomFgTip handler

Using: onmouseover="tip.show('parent element id','title','contents')"

@author Oliver Leisalu
@package DomFg 
@created 27.07.2009
*/
var tip = new fg_toolTip();
function fg_toolTip(){

	var currentElement = null;

	this.show = function( elementId, title, contents ){
		
		if( this.currentElement != null ) {
			this.currentElement.onmousemove = null;
			this.currentElement.onmouseout = null;
		}
		this.currentElement = document.getElementById(elementId);
		
		document.getElementById("fg_toolTipTitle").innerHTML = title;
		document.getElementById("fg_toolTipContents").innerHTML = contents;
		
		this.updateLocation();
		document.getElementById("fg_toolTip").style.display = "";
		document.getElementById("fg_toolTipTitle").style.width = (document.getElementById("fg_toolTipContents").offsetWidth-8)+"px";
		
		this.currentElement.onmousemove = function(){
			tip.updateLocation();
		};
		this.currentElement.onmouseout = function() {
			tip.hide();
		};
	}
	
	this.hide = function(){
		document.getElementById("fg_toolTip").style.display = "none";
		this.currentElement.onmousemove = null;
		this.currentElement.onmouseout = null;
	}
	
	this.updateLocation = function() {
		var pos = getMouseXY();
		document.getElementById("fg_toolTip").style.top = (pos[1]+25)+"px";
		document.getElementById("fg_toolTip").style.left = (pos[0]-10)+"px";
	}
}

/**
Grid functions

@author Oliver Leisalu
@package DomFg 
@created 22.09.2010
*/
function gridOrderBy( gridName, orderByField, orderByDirection ) {
	v = document.getElementById( gridName+'_orderBy'); 
	v.value = 1; 
	
	v = document.getElementById( gridName+'_orderByField'); 
	v.value = orderByField; 
	
	v = document.getElementById( gridName+'_orderByDirection'); 
	v.value = orderByDirection; 
	
	v.form.submit();
}

/**
Image grid drag drop interface

@author Oliver Leisalu
@package DomFg 
@created 27.07.2009
*/
var activeDroppable = null;
$.fn.fg_galleryItem = function(options){
	
	var defaults = {
		'id' : 'default',
		'name' : 'default',
		'separatorQuery' : '#'+options.id+'_separator',
		'orderFunction' : function() {
			$("#"+options.id+"_order").get(0).value = "";
			$(".fg_imageGrid > div").not(':last').each( function() {
				if( this.id != options.id+"_separator") {
					$("#"+options.id+"_order").get(0).value += this.id.split('_')[1]+";";
				}
			});
		}
	};
	var options = $.extend( defaults, options ); 
	options.orderFunction();
		
	return this.each(function( ){
		
		
		$(this).draggable({
			'helper': 'clone',
			'opacity':0.4,
			'distance':10,
			'start': function( event, ui ) {

			},
			'stop': function( event, ui ) {
				$(options.separatorQuery).hide().next().removeClass("fg_imageGridImageOver");
			},
			'drag': function( event, ui ) {
				
				/*$('#order').html(
					(activeDroppable == null ? "element undefined<br>" : "element: "+activeDroppable.text()+" ("+activeDroppable.offset().left+" : "+activeDroppable.offset().top+") <br> ")+
					"separator: "+$("#separator").prev().offset().left+":"+$("#separator").prev().offset().top+"<br> "+
					"helper: "+ui.position.left+":"+ui.position.top+"<br> "+
					"mouse :"+event.pageX+":"+event.pageY );
				*/
				if( activeDroppable == null)
					return;

				var separator = $(options.separatorQuery);
				
				separator.next().removeClass("fg_imageGridImageOver");
				separator.css("clear",'none');
				separator.css("height",separator.next().height()+"px");
				
				// positions element to right
				if( activeDroppable.offset().left + activeDroppable.width()/2 < event.pageX ) {
					activeDroppable.after( separator );
					
					// determine if next item is not on next line
					if( separator.next().offset().top <= event.pageY ) {
						separator.next().addClass("fg_imageGridImageOver");
					}
					
				// positions element to left
				} else {
					
					activeDroppable.before( separator );
					separator.next().addClass("fg_imageGridImageOver");
					
					// determine if previous item is on previous line
					var marginBetweenItems = separator.next().offset().top - separator.prev().offset().top - separator.prev().height();
					if( marginBetweenItems < 0 )
						marginBetweenItems = 0;
						
					//$('#order').html(separator.prev().offset().top+" + "+separator.prev().height()+" + "+marginBetweenItems+" < "+separator.next().offset().top );
					if( separator.prev().offset().top + separator.prev().height() + marginBetweenItems <= separator.next().offset().top ) {
						separator.css('clear','left');
					}
					
				}
				
				
			}
		});
		
		$(this).droppable({
			'tolerance': 'pointer',
			'drop': function( event , ui ) {
				
				$(options.separatorQuery).hide().next().removeClass("fg_imageGridImageOver");
				activeDroppable = null;
				
				if( $(this).offset().left + $(this).width()/2 < event.pageX ) {
					$(this).after( ui.draggable );
				} else {
					$(this).before( ui.draggable );
				}
				
				options.orderFunction();
			},
			'over': function( event, ui ) {
				activeDroppable = $(this);
				$(options.separatorQuery).show().next().addClass("fg_imageGridImageOver");;
			},
			'out' : function( event, ui ) {
				activeDroppable  = null;
				$(options.separatorQuery).hide().next().removeClass("fg_imageGridImageOver");
			}
		});
		

	});
};

/**
Init html editor

@author Oliver Leisalu
@package DomFg 
@created 22.09.2010
*/
function initHtmlEditor( name, imageManagerUrl, templateUrl ) {
	tinyMCE.init({
		mode : "exact",
		elements : name+"-id",
		theme : "advanced",
		width: '100%',
		media_strict: false,
		plugins : "imageManager,flash,safari,advlink,inlinepopups,fullscreen",
		theme_advanced_buttons1 : "undo,redo,|,bold,italic,underline,strikethrough,image,imageManager,link,unlink,forecolor,backcolor,formatselect,|,bullist,numlist,|,cleanup,code,fullscreen",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : false,
		remove_script_host : 0,
		convert_urls : 0,
		imageManagerUrl: imageManagerUrl,
		setup : function(ed) {
			ed.onBeforeSetContent.add(function(ed, o) {
				o.content = o.content.replace(/<\?/gi, "&lt?");
				o.content = o.content.replace(/\?>/gi, "?&gt");
			});
		},
		content_css : templateUrl+"Input/htmlEditor.css"
	});
}